import React, { useState, useEffect } from 'react';
import { Table, Progress, Avatar, message } from 'antd';
import { history } from 'umi';
import { getTaskSubtask } from '../../../../services';
import { getTaskStatus, getTaskSituation, TaskStatus, toNum, TimeFormatHour, TimeFormat } from '../../../../utils';
import styles from '../../MyExecuteDetail.less';

const SubTask = ({ location, activeKey, refreshComp }) => {
    const { query: urlQuery } = location;

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState([]);
    const [subNum, setSubNum] = useState(0);
    const [total, setTotal] = useState(0);
    const [expandedRowKeys, setExpandedRowKeys] = useState([]);

    const renderEllipsis = (text, record) => (
        <div style={{ flex: 1, minWidth: 350, maxWidth: 500, position: 'relative', display: 'inline-block' }}>
            <span
                style={{
                    position: 'absolute',
                    left: 0,
                    right: 0,
                    top: 0,
                    transform: 'translateY(-50%)',
                    overflow: 'hidden',
                    whiteSpace: 'nowrap',
                    textOverflow: 'ellipsis',
                    color: '#ffa808',
                    cursor: 'pointer'
                }}
                title={text}
                onClick={() => {
                    history.push({
                        pathname: '/work/task/taskdetail',
                        query: {
                            id: record.id,
                            activeKey: 'detailMsg'
                        }
                    });
                }}
            >
                {text}
            </span>
        </div>
    );
    const columns = [
        {
            title: '任务名称',
            dataIndex: 'taskName',
            key: 'taskName',
            className: styles.subTaskName,
            // width: 300,
            render: (text, record) => renderEllipsis(text, record)
            // render: (text, record) => (
            //     <div
            //         style={{
            //             display: 'inline-block',
            //             width: '200px',
            //             // maxWidth: '300px',
            //             overflow: 'hidden',
            //             whiteSpace: 'nowrap',
            //             textOverflow: 'ellipsis',
            //             verticalAlign: 'middle'
            //         }}
            //     >
            //         <span
            //             title={record.taskName}
            //             style={{ color: '#ffa808', cursor: 'pointer' }}
            //             onClick={() => {
            //                 history.push({
            //                     pathname: '/work/task/taskdetail',
            //                     query: {
            //                         id: record.id,
            //                         activeKey: 'detailMsg'
            //                     }
            //                 });
            //             }}
            //         >
            //             {record.taskName}
            //         </span>
            //     </div>
            // )
        },
        {
            title: '执行人',
            dataIndex: 'executor',
            key: 'executor',
            width: 200,
            render: (text, record) => (
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    {record.executorPortrait ? (
                        <Avatar
                            style={{ verticalAlign: 'middle' }}
                            size={36}
                            src={record.executorPortrait || ''}
                        ></Avatar>
                    ) : (
                        <Avatar style={{ backgroundColor: '#ff9e00', verticalAlign: 'middle' }} size={36} icon="user" />
                    )}
                    <span style={{ marginLeft: '8px' }}>{record.executor || ''}</span>
                </div>
            )
        },
        {
            title: '任务状态',
            dataIndex: 'taskStatus',
            key: 'taskStatus',
            width: 100,
            render: (text, record) => getTaskStatus(record.taskStatus)
        },
        {
            title: '当前进度',
            dataIndex: 'taskProgress',
            width: 200,
            key: 'taskProgress',
            render: (text, record) => {
                let format = {};
                let color = '#5AD8A6';
                if (toNum(text) >= 100) {
                    format = {
                        format: () => '100%'
                    };
                }
                if (record.taskStatus === TaskStatus.FINISH || record.taskStatus === TaskStatus.CANCEL) {
                    color = '#999999';
                } else if (record.taskStatus === TaskStatus.PAUSE) {
                    color = '#FFA784';
                }
                return (
                    <div style={{ display: 'flex' }}>
                        <Progress
                            className={styles.taskProgress}
                            strokeColor={color}
                            percent={Number(record.taskProgress)}
                            size="small"
                            {...format}
                        />
                    </div>
                );
            }
        },
        {
            title: '实际工时',
            dataIndex: 'actualWorkDuration',
            key: 'actualWorkDuration',
            width: 250,
            render: (text, record) => (
                <div
                    style={{
                        width: '250px',
                        overflow: 'hidden',
                        whiteSpace: 'nowrap',
                        textOverflow: 'ellipsis'
                    }}
                    title={
                        record.actualWorkDuration && record.actualWorkDuration !== 0
                            ? `${TimeFormatHour(record.actualWorkDuration)} (${TimeFormat(record.actualWorkDuration)})`
                            : '0小时 (0天0小时0分钟)'
                    }
                >
                    {record.actualWorkDuration && record.actualWorkDuration !== 0
                        ? `${TimeFormatHour(record.actualWorkDuration)} (${TimeFormat(record.actualWorkDuration)})`
                        : '0小时 (0天0小时0分钟)'}
                </div>
            )
        },
        {
            title: '完成执行情况',
            dataIndex: 'progressSituation',
            key: 'progressSituation',
            width: 100,
            render: (text, record) => getTaskSituation(record.progressSituation)
        },
        { title: '任务编号', dataIndex: 'taskNo', key: 'taskNo', width: 100 }
    ];
    // 处理数据
    const getData = list => {
        // 删除所有children
        list.forEach(item => {
            delete item.children;
        });
        // 将数据存储为 以 id 为 KEY 的 map 索引数据列
        const map = {};
        list.forEach(item => {
            map[item.id] = item;
        });
        const newList = [];
        list.forEach(item => {
            // 以当前遍历项的pid,去map对象中找到索引的id
            const parent = map[item.parentTaskId];
            // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到他对应的父级中
            if (parent) {
                (parent.children || (parent.children = [])).push(item);
            } else {
                // 如果没有在map中找到对应的索引ID,那么直接把当前的item添加到 val结果集中，作为顶级
                newList.push(item);
            }
        });
        return newList;
    };
    const fetchSubtask = async () => {
        setLoading(true);
        const params = { id: urlQuery.id };
        const result = await getTaskSubtask(params);

        if (result.code === 10000) {
            setData(getData(result.data));
            const newDate = getData(result.data);
            let num = 0;
            newDate.forEach(item => {
                if (item.actualWorkDuration) {
                    num += item.actualWorkDuration;
                }
            });
            setTotal(num);
            setSubNum(result.data.length);
            setExpandedRowKeys([]);
        } else {
            message.error(result.msg);
        }
        setLoading(false);
    };

    const handleRowExpanded = expandedRows => {
        setExpandedRowKeys(expandedRows);
    };

    useEffect(() => {
        if (activeKey === 'sonTask') {
            fetchSubtask();
        }
    }, [activeKey, refreshComp]);
    return (
        <div>
            <div style={{ marginBottom: '20px' }}>
                <span style={{ marginRight: '16px' }}>子任务总数：{subNum}</span>
                <span>
                    子任务实际总工时：
                    {total !== 0 ? `${TimeFormatHour(total)} (${TimeFormat(total)})` : '0小时 (0天0小时0分钟)'}
                </span>
            </div>
            <Table
                loading={loading}
                // defaultExpandAllRows
                expandedRowKeys={expandedRowKeys}
                onExpandedRowsChange={handleRowExpanded}
                columns={columns}
                rowKey="id"
                scroll={{ x: 'max-content' }}
                dataSource={data}
                pagination={false}
            />
        </div>
    );
};

export default SubTask;
